//
//  NetworkHandler.m
//  UI_homework15
//
//  Created by Eiwodetianna on 14-6-30.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NetworkHandler.h"

@implementation NetworkHandler

- (void)getDataWithURLString:(NSString *)urlStr complention:(BLOCK)block
{
    [self setPassValue:block];
    NSString *str = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.f];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data != nil) {
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            [self passValue](object);
            
            
        }
    }];
}

+ (void)connectNetGetDataWithURLString:(NSString *)urlStr complention:(BLOCK)block
{
    NetworkHandler *net = [[NetworkHandler alloc] init];
    [net getDataWithURLString:urlStr complention:block];
//    [net autorelease];
}

- (void)getDataWithURLString:(NSString *)urlStr URLBodyString:(NSString *)bodyStr complention:(BLOCK)block
{
    [self setPassValue:block];
    
    NSString *str = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.f];
    
    [request setHTTPMethod:@"POST"];
    
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPBody:bodyData];
    
    // 连接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data != nil) {
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            [self passValue](object);
           
        }
    }];
}

+ (void)connectNetGetDataWithURLString:(NSString *)urlStr URLBodyString:(NSString *)bodyStr complention:(BLOCK)block
{
    NetworkHandler *net = [[NetworkHandler alloc] init];
    [net getDataWithURLString:urlStr URLBodyString:bodyStr complention:block];
//    [net autorelease];
}

@end
